<template>
  <div class="attendance_result_report">

    <div class="tool">
      <div class="select">


        <el-form :inline="true">


<!--          <el-form-item label="部门:">
            <el-select v-model="form.dept" placeholder="请选择部门..." @change="deptChange" size="small"
                       filterable clearable>
              <el-option :label="item.deptLevel2" :value="item.deptLevel2" v-for="item in deptList">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="组别:">
            <el-select v-model="form.groupName" placeholder="请选择组别..." size="small"
                       filterable clearable>
              <el-option :label="item.groupName" :value="item.groupName" v-for="item in groupList">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="异常情况:">
            <el-select v-model="form.exceptionDes" placeholder="请选择..." size="small" filterable clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="迟到" value="迟到"></el-option>
              <el-option label="早退" value="早退"></el-option>
              <el-option label="旷工" value="旷工"></el-option>
              <el-option label="工作日排休" value="工作日排休"></el-option>
              <el-option label="超时加班未申请" value="超时加班未申请"></el-option>
              <el-option label="请假开始/结束未打开" value="请假开始/结束未打开"></el-option>
              <el-option label="请假时间不规范" value="请假时间不规范"></el-option>
              <el-option label="请假时间不足半天" value="请假时间不足半天"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名:">
            <el-select v-model="form.jobNumber" placeholder="请选择员工姓名..." value-key="userId" size="small"
                       @change="handleUserChange"
                       filterable clearable>
              <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.jobNo" v-for="item in $store.state.userList">
                <span style="float: left">{{ item.userName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
              </el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item label="日期:">
            <el-date-picker size="small"
                            @change="dateChange"
                            v-model="attendanceDate"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            align="left"
                            :picker-options="pickerOptions"
                            :clearable="false"
                            value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleChange" size="small">筛选</el-button>
            <el-button type="primary" @click="reSet" size="small" icon="el-icon-refresh">重置
            </el-button>
          </el-form-item>

<!--          <el-form-item>
            <ToolBar :update-disable="multipleSelection.length!==1" :update-data="updateById" :show-all="false"
                     :delete-disable="multipleSelection.length===0" :delete-data="deleteById"
                     :add-data="setAddDialogVisible" :show-multiple="false"></ToolBar>
          </el-form-item>-->
          <el-form-item>
<!--            <el-button type="primary" @click="goGetData" size="small">异常监控</el-button>-->
<!--            <el-button type="primary" @click="exportData" size="small">导出</el-button>
            <el-button type="primary" @click="exportData1" size="small">导出全部</el-button>-->



          </el-form-item>


        </el-form>
      </div>
      <el-dialog title="异常监控" :visible.sync="getDataDialogFormVisible" center width="35%">
        <el-row>
          <el-form :model="form" label-width="3rem">
            <el-form-item label="姓名:">
              <el-select v-model="form.userId" placeholder="请选择员工姓名..." value-key="userId" size="small" class="w100"
                         @change="handleUserChange"
                         filterable clearable>
                <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.userId" v-for="item in $store.state.userList">
                  <span style="float: left">{{ item.userName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期:">
              <el-date-picker  v-model="attendanceDate" size="small"
                               type="daterange"
                               style="width: 100%"
                               align="left"
                               unlink-panels
                               @change="dateChange"
                               range-separator="至"
                               start-placeholder="开始日期"
                               end-placeholder="结束日期"
                               :picker-options="pickerOptions"
                               :clearable="false"
                               value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="getDataDialogFormVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="checkData">确 定</el-button>
        </div>
      </el-dialog>

    </div>
    <el-table
        id="table-detail"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column label="日期" prop="createTime" min-width="50">
        <template slot-scope="scope" v-if="scope.row.createTime">
          {{ scope.row.createTime|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="接口名称" prop="capiName" width="100">
<!--        <template slot-scope="scope">
          <span @click="getDingAttendanceDetail(scope.row)"> {{ scope.row.fullname }}</span>
        </template>-->
      </el-table-column>
      <el-table-column label="接口描述" prop="capiDes" :show-overflow-tooltip="true" width="100">
      </el-table-column>
      <el-table-column label="异常情况描述" prop="cexceptions" :show-overflow-tooltip="true" min-width="200">
      </el-table-column>
      <el-table-column label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleRetry(scope.row)">重试
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          hide-on-single-page
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[size, size*2, size*3, size*4,total]"
          :page-size=size
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <el-drawer
        title="打卡数据"
        :visible.sync="drawer"
        :direction="direction">
      <div slot="title">
        <h2><span>{{ row.fullname }}打卡数据</span><span
            class="float-end">（{{ row.attendanceDate|formatDateBirth }}）</span></h2>
      </div>
      <div style="margin-left: 2rem">
        <el-descriptions :title="'打卡类型:'+item.checkType" v-for="item in attendanceResultList" column=1
                         :key="item.id">
          <el-descriptions-item label="标准打卡时间">{{ item.baseCheckTime|formatDate }}</el-descriptions-item>
          <el-descriptions-item label="实际打卡时间">{{ item.userCheckTime|formatDate }}</el-descriptions-item>
          <el-descriptions-item label="数据来源">{{ item.sourceType }}</el-descriptions-item>
          <el-descriptions-item label="打卡结果">{{ item.timeResult }}</el-descriptions-item>
          <el-descriptions-item label="审批单"><span @click="getApprove(item)">{{ item.procinstId }}</span>
          </el-descriptions-item>
        </el-descriptions>
        备注：
        <el-tag type="danger" v-text="row.summary"></el-tag>
        <el-drawer
            title="审批单详情"
            :append-to-body="true"
            :before-close="handleClose"
            :visible.sync="innerDrawer">
          <div slot="title">
            <h2>审批单详情</h2>
          </div>
          <div style="margin-left: 2rem">
            <el-descriptions :title="'审批单名称:'+approve.tagName" column=1 v-if="approve!=null">
              <el-descriptions-item label="姓名">{{ approve.userName }}</el-descriptions-item>
              <el-descriptions-item label="工号">{{ approve.jobNo }}</el-descriptions-item>
              <el-descriptions-item label="时长">{{ approve.duration }}</el-descriptions-item>
              <el-descriptions-item label="时长单位">{{ approve.durationUnit }}</el-descriptions-item>
              <el-descriptions-item label="开始时间">{{ approve.beginTime|formatDate }}</el-descriptions-item>
              <el-descriptions-item label="结束时间">{{ approve.endTime|formatDate }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-drawer>
      </div>

    </el-drawer>
    <el-drawer :title="'考勤结果'+(isAdd?'添加':'修改')"
               :visible="drawer1"
               :before-close="handleClose"
               :direction="direction">
      <el-row style="padding:0 1rem 0 2rem">
        <el-form :model="attendanceResultReport" label-position="left" :rules="rules" ref="attendance">
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="fullname">
            <el-input v-model="attendanceResultReport.fullname" :disabled="!isAdd"></el-input>
          </el-form-item>
          <el-form-item label="工号" :label-width="formLabelWidth" prop="jobno">
            <el-input v-model="attendanceResultReport.jobno" :disabled="!isAdd"></el-input>
          </el-form-item>
          <el-form-item label="出勤日期" :label-width="formLabelWidth" prop="attendancedate">
            <el-date-picker v-model="attendanceResultReport.attendancedate" class="w100"
                            :disabled="!isAdd"></el-date-picker>
          </el-form-item>
          <el-form-item label="上班打卡" :label-width="formLabelWidth" prop="onDuty">
            <el-date-picker disabled v-model="attendanceResultReport.onDuty"></el-date-picker>
            <el-time-picker disabled v-model="attendanceResultReport.onDuty"></el-time-picker>
          </el-form-item>
          <el-form-item label="下班打卡" :label-width="formLabelWidth" prop="offDuty" >
            <el-date-picker disabled v-model="attendanceResultReport.offDuty"></el-date-picker>
            <el-time-picker disabled v-model="attendanceResultReport.offDuty"></el-time-picker>
          </el-form-item>
          <el-form-item label="基本出勤" :label-width="formLabelWidth" prop="basicattendance">
            <el-input disabled v-model="attendanceResultReport.basicattendance" @change="numberChange" type="number"></el-input>
          </el-form-item>
          <el-form-item label="基本加班" :label-width="formLabelWidth" prop="basicovertime">
            <el-input disabled v-model="attendanceResultReport.basicovertime" @change="numberChange"></el-input>
          </el-form-item>
          <el-form-item label="连班加班" :label-width="formLabelWidth" prop="continuousshifthours">
            <el-input disabled v-model="attendanceResultReport.continuousshifthours" @change="numberChange"></el-input>
          </el-form-item>
          <el-form-item label="超时加班" :label-width="formLabelWidth" prop="overtime">
            <el-input disabled v-model="attendanceResultReport.overtime" @change="numberChange"></el-input>
          </el-form-item>
          <el-form-item label="总出勤" :label-width="formLabelWidth" prop="totalduration">
            <el-input v-model="attendanceResultReport.totalduration" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth" prop="totalduration">
            <el-input v-model="attendanceResultReport.summaryPeople" ></el-input>
          </el-form-item>

          <el-form-item style="text-align: right">
            <el-button @click="edit('attendance')" type="primary">确认</el-button>
            <el-button @click="drawer1=false">取消</el-button>
          </el-form-item>
        </el-form>

      </el-row>
    </el-drawer>
  </div>
</template>

<script>
import ToolBar from "@/components/common/ToolBar";
import moment from "moment";

export default {
  name: "dingdingYcjk",
  components: {ToolBar},
  data() {
    var checkBasicAttendance = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('基本出勤时间不能为空'));
      }
      setTimeout(() => {
        if (value > 8) {
          callback(new Error('基本出勤时间不超过8小时...'));
        } else {
          callback();
        }

      }, 1000);
    };
    return {
      attendanceResultReport: {},
      currentPage: 1,
      total: 0,
      size: 10,
      tableData: [],
      dingUsersListName: null,
      dingUsersList: [],
      userList: [],
      isDowload: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      dialogFormVisible: false,
      getDataDialogFormVisible: false,
      form: {
        start: moment().format("YYYY-MM-DD"),
        end: moment().format("YYYY-MM-DD"),
        userId: null,
        name: null,
        workDate: null,
        exceptionDes: null,
        limit: 12,
        page: 1
      },
      formLabelWidth: '80px',
      timeResultList: [
        {
          label: "正常",
          value: "Normal",
        },
        {
          label: "早退",
          value: "Early",
        }, {
          label: "迟到",
          value: "Late",
        }, {
          label: "严重迟到",
          value: "SeriousLate",
        }, {
          label: "旷工迟到",
          value: "Absenteeism",
        }, {
          label: "未打卡",
          value: "NotSigned",
        },
      ],
      drawer: false,
      direction: 'rtl',
      attendanceResultList: [],
      popoverShow: false,
      row: {},
      attendanceDate: [moment().format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")],
      approve: {},
      innerDrawer: false,
      drawer1: false,
      multipleSelection: [],
      isAdd: false,
      rules: {
        basicattendance: [
          {validator: checkBasicAttendance, trigger: "blur"}
        ]
      },
      deptList: [],
      groupList: []

    }
  },
  created() {
    this.getDataList()

  },
  mounted() {
    this.getDeptList()
  },
  methods: {
    dateChange() {
      this.form.start = this.attendanceDate[0]
      this.form.end = this.attendanceDate[1]
    },
    numberChange() {
      this.attendanceResultReport.totalduration =
          parseFloat(this.attendanceResultReport.basicattendance)
          + parseFloat(this.attendanceResultReport.basicovertime) + parseFloat(this.attendanceResultReport.continuousshifthours) + parseFloat(this.attendanceResultReport.overtime)
    },
    setAddDialogVisible() {
      this.drawer1 = true
      this.isAdd = true
      this.attendanceResultReport = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getApprove(item) {
      console.log("Item;", item)
      const id = item.procinstId + item.userId
      axios.get("/ding_approve_list/get/" + id).then(res => {
        if (res.data.success) {
          this.innerDrawer = true
          this.approve = res.data.data
          console.log("Approve:", res.data.data)
        } else {
          this.approve = null
        }
      })
    },
    getDeptList() {
      axios.get("/fin_user_roster/deptList").then(res => {
        if (res.data.success) {
          this.deptList = res.data.data
        } else {
          this.deptList = []
        }
      })
    },
    deptChange() {
      if (this.form.dept !== null) {
        this.getGroupList()

      }

    },
    getGroupList() {
      axios.get("/fin_user_roster/groupList?dept=" + this.form.dept).then(res => {
        if (res.data.success) {
          this.groupList = res.data.data
        } else {
          this.groupList = []
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.drawer1 = false
            this.attendanceResultReport = {}
            done();
          })
          .catch(_ => {
          });
    },
    tableRowClassName({row, rowIndex}) {
      if ((row.basicattendance < 8 || row.basicattendance === null) && row.week !== '七') {
        return 'error-row';
      }
      return '';
    },
    goGetData() {
      this.getDataDialogFormVisible = true
    },
    handleEdit(row) {
      this.attendanceResultReport = row
      this.drawer1 = true
      this.isAdd = false

    },
    edit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.attendanceResultReport.updateuserid = this.$store.state.userInfo.id
          axios.post("/attendance_result_report/update/" + this.$store.state.userInfo.id + "/" + this.$store.state.userInfo.name, this.attendanceResultReport).then(res => {
            if (res.data.success) {
              this.$tools.showMessage(res.data.message, "success")
              this.getDataList()
              this.drawer1 = false
              this.attendanceResultReport = {}
            } else {
              this.$tools.showMessage(res.data.message, "error")
            }
          })
        }
      })

    },
    handleRetry(row) {
      this.$tools.showMessageBox("确认要进行重试操作吗？", "操作确认", "warning").then(confirm => {
        axios.post("/ycjk/ffycjk/retry", row).then(res => {
          if (res) {
            this.$tools.showMessage("操作成功！", "success")
            this.getDataList()
          } else {
            this.$tools.showMessage("操作成功！", "error")
          }
        })
      }).catch(cancel => {

      })
    },
    getDataList() {
      this.dialogFormVisible = false
      // this.form.start=this.attendanceDate[0]
      // this.form.end=this.attendanceDate[1]
      this.form.limit = this.size;
      this.form.page = this.currentPage;
      console.log("查询数据：", this.form)
      axios.get("/ycjk/ffycjk/list", {params:this.form}).then(res => {
        if (res.status === 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.pages = res.data.pages;
        } else {
          this.tableData = []
          this.total = 0
          this.pages = 1
        }

      }).catch(error=>{
        console.log(error);
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getDataList()
    },
    goSearch() {
      this.dialogFormVisible = true

    },
    reSet() {
      this.currentPage = 1;
      this.form = {
        start: moment().format("YYYY-MM-DD"),
        end: moment().format("YYYY-MM-DD"),
        userId: null,
        workDate: null,
        exceptionDes: null,
        limit: 12,
        page: 1
      }
      this.getDataList()
    },
    handleChange() {
      this.currentPage = 1;
      this.getDataList()
    },
    handleUserChange() {
      // this.form.userId=
      console.log('Form:', this.form)
    },
    deleteById() {
      console.log("用户扫描删除")
      this.$tools.showMessageBox("确认删除选择的：" + this.multipleSelection.length + "条考勤数据？", "操作确认", "warning").then(confirm => {
        axios.post("/attendance_result_report/deleteBatch" + this.$store.state.userInfo.id + "/" + this.$store.state.userInfo.name, this.multipleSelection).then(res => {
          if (res.data.success) {
            this.$tools.showMessage(res.data.message, "success")
            this.getDataList()
          } else {
            this.$tools.showMessage(res.data.message, "error")
          }
        })
      }).catch(cancel => {
        this.$tools.showMessage("操作取消！", "info")
      })
    },
    updateById() {
      console.log("用户扫描修改")

      this.handleEdit(this.multipleSelection[0])
    },
    checkData() {
      this.form.start = moment(this.attendanceDate[0]).format("YYYY-MM-DD")
      this.form.end = moment(this.attendanceDate[1]).format("YYYY-MM-DD")
      console.log("查询数据：", this.form)
      this.$tools.openLoading()
      axios.post("/ycjk/attendance/check", this.form).then(res => {
        if (res.status === 200) {
          this.getDataList()
          this.$tools.closeLoading();
          this.getDataDialogFormVisible = false;
        }
      }).catch(error =>{
        this.$tools.showMessage("考勤结果异常检查出错！","error");
        console.log(error);
      })
    },
    getDingAttendanceDetail(row) {
      console.log("Row:", row)
      this.row = row
      const data = {
        workDate: row.attendancedate,
        userId: row.userid
      }
      axios.post("/ding_attendance_result/getDetail", data).then(res => {
        console.log("Res:", res)
        if (res.data.success) {
          this.attendanceResultList = res.data.data
        } else {
          this.attendanceResultList = []
        }
      })
      this.drawer = true
    },
    exportData() {
      this.isDowload = true
      let excelName = '四川瀚海' + moment(this.form.salaryYearMonth).format('YYYY年MM月DD日') + (this.form.dept === undefined ? '' : this.form.dept) + (this.form.groupName === undefined ? '' : this.form.groupName) + '考勤信息.xlsx';
      var xlsxParam = {raw: true};//转换成excel时，使用原始的格式
      // 克隆节点
      let tables = document.getElementById("table-detail").cloneNode(true);
      // 判断是否为固定列，解决（为固定列时，会重复生成表格）
      if (tables.querySelector('.el-table__fixed') !== null) {
        tables.removeChild(tables.querySelector('.el-table__fixed'))
      }
      let table_book = this.$XLSX.utils.table_to_book(tables, xlsxParam);
      var table_write = this.$XLSX.write(table_book, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        this.$FileSaver.saveAs(
            new Blob([table_write], {type: "application/octet-stream"}),
            excelName
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, table_write);
      }
      this.isDowload = false
      this.size = 12
      this.currentPage = 1
      this.getDataList()
      return table_write;

    },
    exportData1() {
      this.size = this.total
      axios.post("/attendance_result_report/list/" + this.currentPage + "/" + this.size, this.form).then(res => {
        console.log("详细：", res)
        if (res.data.success) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.pages = res.data.data.pages
        } else {
          this.tableData = []
          this.total = 0
          this.pages = 1
          this.$tools.showMessage(res.data.message, 'error')
        }

      })
      if (this.tableData.length === this.size) {
        this.exportData()
      }
    }

  },

}
</script>

<style scoped lang="less">
.attendance_result_report {
  .select {
    //margin-bottom: 0.1rem;
    display: inline-flex !important;
  }

  .el-input--suffix .el-input__inner {
    padding-right: 0;
  }
}

</style>
